﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Net;
using System.IO;
using NeuralStock.Entities;
using NeuralStock.Common;
using NeuralStock.Common.WebData;
using System.Text.RegularExpressions;
using System.Globalization;

namespace NeuralStock.Tools
{
    public class GpwCompanyIndicatorsDownloader : BaseDownloader
    {
        public List<GpwCompanyIndicatorsData> GetData()
        {
            string filePath = Path.Combine(DirectoryRepository.WebDataDirectory, "CompanyIndicators.html");
            HtmlDocument doc = DownloadAndLoad(WebsiteRepository.GpwCompanyIndicators, filePath);

            return RetrieveDataFromHtmlFile(doc);
        }

        private List<GpwCompanyIndicatorsData> RetrieveDataFromHtmlFile(HtmlDocument doc)
        {
            List<GpwCompanyIndicatorsData> results = new List<GpwCompanyIndicatorsData>();

            var tableRows = doc.DocumentNode.SelectNodes("//table[@class='tab03']//tr");
            var companyDataTR = tableRows.Skip(3);

            foreach (var row in companyDataTR)
            {
                var dataRows = row.ChildNodes.Where(x => x.Name == "td").ToList();
                if (dataRows.Count >= 6)
                {
                    GpwCompanyIndicatorsData entity = new GpwCompanyIndicatorsData();
                    entity.CompanyName = dataRows[4].InnerText;
                    entity.NumberOfShares = ParseDecimal(dataRows[5].InnerText) / 1000;
                    entity.Sector = dataRows[3].InnerText;
                    entity.PE = ParseDecimal(dataRows[11].InnerText);
                    entity.PBV = ParseDecimal(dataRows[10].InnerText);
                    results.Add(entity);
                }  
            }

            return results;
        }
    }
}
